<!-- 数据库表Column管理抽屉界面 -->
<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="displayModuleTitle" width="88%">
    <BasicTable
      @register="registerTable"
      :can-resize="true"
      :bordered="true"
      :striped="false"
      :loading="false"
      :data-source="tableData"
    >
      <template #toolbar>
        <a-button type="success" size="small" @click="onAddButtonClick()"
          ><PlusOutlined /> 新增
        </a-button>

        <a-button type="success" size="small" @click="onAutoAddButtonClick()"
          ><PlusOutlined /> 自动获取列生成
        </a-button>
      </template>

      <!-- 是否为主键 -->
      <template #isPrimary="{ record }">
        <template v-if="record.isprimary === true">
          <Tag :color="'green'">是</Tag>
        </template>
        <template v-if="record.isprimary === false">
          <Tag>否</Tag>
        </template>
      </template>

      <!-- 是否非空 -->
      <template #isNotNull="{ record }">
        <template v-if="record.notnull === true">
          <Tag :color="'green'">是</Tag>
        </template>
        <template v-if="record.notnull === false">
          <Tag>否</Tag>
        </template>
      </template>

      <!-- 是否在表格中显示 -->
      <template #isqrshow="{ record }">
        <template v-if="record.qrshow === true">
          <Tag :color="'green'">是</Tag>
        </template>
        <template v-if="record.qrshow === false">
          <Tag>否</Tag>
        </template>
      </template>

      <!-- 是否在表单中显示 -->
      <template #isefshow="{ record }">
        <template v-if="record.efshow === true">
          <Tag :color="'green'">是</Tag>
        </template>
        <template v-if="record.efshow === false">
          <Tag>否</Tag>
        </template>
      </template>

      <!-- 是否作为查询条件 -->
      <template #isqcflag="{ record }">
        <template v-if="record.qcflag === true">
          <Tag :color="'green'">是</Tag>
        </template>
        <template v-if="record.qcflag === false">
          <Tag>否</Tag>
        </template>
      </template>

      <!-- 是否为必须查询条件 -->
      <template #isqcnotnull="{ record }">
        <template v-if="record.qcnotnull === true">
          <Tag :color="'green'">是</Tag>
        </template>
        <template v-if="record.qcnotnull === false">
          <Tag>否</Tag>
        </template>
      </template>

      <!-- 渲染数据类型列为文字显示 -->
      <template #datatypeRender="{ record }">
        <div v-for="(item, index) in columnOptions.datatypeOptions" :key="index">
          <span v-if="item.value == record.datatype">{{ item.label }}</span>
        </div>
      </template>

      <!-- 渲染列类型列为文字显示 -->
      <template #coltypeRender="{ record }">
        <div v-for="(item, index) in columnOptions.coltypeOptions" :key="index">
          <span v-if="item.value == record.coltype">{{ item.label }}</span>
        </div>
      </template>

      <!-- 渲染查询条件比较类型列为文字显示 -->
      <template #qccmptypeRender="{ record }">
        <div v-for="(item, index) in columnOptions.whereconditionOptions" :key="index">
          <span v-if="item.value == record.qccmptype">{{ item.label }}</span>
        </div>
      </template>

      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              label: '编辑',
              onClick: onEditButtonClick.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              label: '删除',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                confirm: onDeleteButtonClick.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <EditDBTbleColumnFormModal
      @register="registerEditColumnFormModal"
      @success="getDBTableColumn"
    />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, reactive } from 'vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';

  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { PlusOutlined } from '@ant-design/icons-vue';

  import { dbTableColumnColumns } from './dbtablecolumn.data';
  import {
    queryDBTableColumn,
    deleteDBTableColumn,
    getAddColumnsInfo,
  } from '/@/api/platform/dbTableColumn';
  import EditDBTbleColumnFormModal from './EditDBTableColumnModal.vue';
  import { queryEnumOptions } from '/@/api/platform/enum';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { useModal } from '/@/components/Modal';
  import { Tag } from 'ant-design-vue';

  export default defineComponent({
    name: 'DBTableColumnMenagement',
    components: {
      BasicDrawer,
      BasicTable,
      TableAction,
      PlusOutlined,
      EditDBTbleColumnFormModal,
      Tag,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      /**
       * 组件之间传递数据的统一属性，包含模块名称、操作类型、数据ID
       */
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();

      /**
       * 显示的模块标题，用于显示在弹出框中的标题
       */
      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });

      const [registerEditColumnFormModal, { openModal: openEditColumnFormModal }] = useModal();

      const { createMessage } = useMessage();

      // 数据库表列数据
      const tableData = ref([]);

      //列的选择项数据对象
      const columnOptions = reactive({
        datatypeOptions: [],
        coltypeOptions: [],
        whereconditionOptions: [],
      });

      const [registerDrawer] = useDrawerInner((data) => {
        //接收父组件传递的数据
        if (data != undefined && data != null) {
          qcUnifyProps.value = unref(data);
          console.log('接收的对象', qcUnifyProps.value);
        }
        handleColumnOptions();
        getDBTableColumn();
      });

      const [registerTable] = useTable({
        title: '数据库表列管理',
        columns: dbTableColumnColumns,
        showTableSetting: true,
        bordered: true,
        size: 'small',
        actionColumn: {
          width: 140,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
      });

      /**
       * 获取指定数据库表编码所有的列
       */
      function getDBTableColumn() {
        tableData.value = [];

        if (!qcUnifyProps.value?.dataId) {
          // 如果数据库表无效，不做处理
        } else {
          queryDBTableColumn(qcUnifyProps.value?.dataId)
            .then((res) => {
              console.log('res', res);
              if (res != undefined && res != null && res.length > 0x0) {
                tableData.value = res;
              }
            })
            .catch((ex) => {
              console.log('catch ', ex);
              createMessage.error(ex.msg);
            });
        }
      }

      /**
       * 处理数据库表列的选择项数据
       */
      function handleColumnOptions() {
        // 清空选择项
        columnOptions.datatypeOptions = [];
        columnOptions.coltypeOptions = [];
        columnOptions.whereconditionOptions = [];
        // 查询处理选择项
        queryEnumOptions('DataTypeEnum,ColumnTypeEnum,WhereConditionTypeEnum')
          .then((res) => {
            // console.log('option res', res);
            if (res != undefined && res != null && res.length > 0x0) {
              for (let i in res) {
                // console.log('i', res[i]);
                if (res[i].enumName == 'DataTypeEnum') {
                  res[i].options.forEach((option) => {
                    let datatypeOption = {
                      value: Number.parseInt(option.key),
                      label: option.value,
                    };
                    columnOptions.datatypeOptions.push(datatypeOption);
                  });
                }
                if (res[i].enumName == 'ColumnTypeEnum') {
                  res[i].options.forEach((option) => {
                    let coltypeOption = {
                      value: Number.parseInt(option.key),
                      label: option.value,
                    };
                    columnOptions.coltypeOptions.push(coltypeOption);
                  });
                }
                if (res[i].enumName == 'WhereConditionTypeEnum') {
                  res[i].options.forEach((option) => {
                    let qccmptypeOption = {
                      value: Number.parseInt(option.key),
                      label: option.value,
                    };
                    columnOptions.whereconditionOptions.push(qccmptypeOption);
                  });
                }
              }
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 新增按钮事件，打开新增表单
       */
      function onAddButtonClick() {
        //构造父组件给子组件传值对象
        //传递数据库表编码tableCode，列的下拉选择项对象columnOptions
        let propsData: QcUnifyTransToChildProps = {
          moduleName: qcUnifyProps.value?.moduleName + '列管理',
          operateType: OperationTypeEnum.ADD,
          dataId: { tableCode: qcUnifyProps.value?.dataId, columnOptions: columnOptions },
        };
        openEditColumnFormModal(true, propsData);
      }

      function onAutoAddButtonClick() {
        getAddColumnsInfo(qcUnifyProps.value?.dataId)
          .then((res) => {
            console.log('res', res);
            createMessage.success(res, 3);
            getDBTableColumn();
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 编辑按钮事件，打开编辑表单
       */
      function onEditButtonClick(record: Recordable) {
        //构造父组件给子组件传值对象
        //传递数据库表编码tableCode，列编码code，列的下拉选择项对象columnOptions
        let propsData: QcUnifyTransToChildProps = {
          moduleName: qcUnifyProps.value?.moduleName + '列管理',
          operateType: OperationTypeEnum.EDIT,
          dataId: { tableCode: record.tbcode, code: record.code, columnOptions: columnOptions },
        };
        openEditColumnFormModal(true, propsData);
      }

      /**
       * 删除按钮事件
       */
      function onDeleteButtonClick(record: Recordable) {
        deleteDBTableColumn(record.tbcode, record.code)
          .then((res) => {
            // console.log('res', res);
            //res判断结果：同时==undefined和null
            if (res == undefined && (res == null || Object.keys(res).length == 0)) {
              createMessage.success('删除成功。', 2);
              getDBTableColumn();
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      return {
        registerDrawer,
        registerTable,
        displayModuleTitle,
        getDBTableColumn,
        tableData,
        onAddButtonClick,
        onAutoAddButtonClick,
        onEditButtonClick,
        onDeleteButtonClick,
        registerEditColumnFormModal,
        handleColumnOptions,
        columnOptions,
      };
    },
  });
</script>
